package org.openkoala.koala.popup;

import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.openkoala.koala.console.ConsoleFactory;
import org.openkoala.koala.exception.KoalaException;
import org.openkoala.koala.mojo.SecurityUpdateParse;
import org.openkoala.koala.widget.Security;

/**
 * 项目右键点击“添加权限管理”时运行的action
 * @author xmfang
 *
 */
public class AddSecurityModuleAction extends SecurityModuleBaseAction {
	
	@Override
	public void run(IAction arg0) {
		if (!initAndVerify()) {
			return;
		}
		
		AddSecurityModuleDialog dialog = new AddSecurityModuleDialog(shell, this);
		dialog.open();
	}

	public void AddSecuritySystemToModule(final Security security) {
		ConsoleFactory.showConsole();
		ProgressMonitorDialog monitorDialog = new ProgressMonitorDialog(shell);
		try {
			monitorDialog.run(true, true, new IRunnableWithProgress() {
				@Override
				public void run(IProgressMonitor monitor) throws InvocationTargetException,
						InterruptedException {
					monitor.beginTask("添加统一认证系统...", 3);
					monitor.worked(1);
					
					monitor.setTaskName("生成统一认证系统...");
					try {
						SecurityUpdateParse.updateSecurity(getProject(), getModule(), security);
					} catch (KoalaException e) {
						e.printStackTrace();
					}
					monitor.worked(2);
					
					monitor.setTaskName("刷新项目...");
					try {
						getSelectedResource().refreshLocal(IResource.DEPTH_INFINITE, null);
					} catch (CoreException e) {
						e.printStackTrace();
					}
					
					monitor.worked(3);
					monitor.done();
				}
			});
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}
